package org.jeecg.common.mybatis;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.binding.MapperMethod.ParamMap;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.ReflectHelper;
import org.jeecg.common.util.SpringContextUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Properties;

/**
 * mybatis拦截器，自动注入创建人、创建时间、修改人、修改时间
 *
 * @Author scott
 * @Date 2019-01-19
 */
@Slf4j
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {

//    @Autowired
    private static ISysBaseAPI sysBaseAPI;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        String sqlId = mappedStatement.getId();
        log.debug("------sqlId------" + sqlId);
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        log.debug("------sqlCommandType------" + sqlCommandType);

        if (parameter == null) {
            return invocation.proceed();
        }
        LoginUser sysUser = JwtUtil.getLoginUser();
        if (SqlCommandType.INSERT == sqlCommandType) {
            Field[] fields = ReflectHelper.getAllFields(parameter);
            for (Field field : fields) {
                this.setFieldValue(field, parameter, sysUser, 1);
            }
        }
        if (SqlCommandType.UPDATE == sqlCommandType) {
            Field[] fields = null;
            if (parameter instanceof ParamMap) {
                ParamMap<?> p = (ParamMap<?>) parameter;
                //update-begin-author:scott date:20190729 for:批量更新报错issues/IZA3Q--
                if (p.containsKey("et")) {
                    parameter = p.get("et");
                } else {
                    parameter = p.get("param1");
                }
                //update-end-author:scott date:20190729 for:批量更新报错issues/IZA3Q-

                //update-begin-author:scott date:20190729 for:更新指定字段时报错 issues/#516-
                if (parameter == null) {
                    return invocation.proceed();
                }
                //update-end-author:scott date:20190729 for:更新指定字段时报错 issues/#516-

                fields = ReflectHelper.getAllFields(parameter);
            } else {
                fields = ReflectHelper.getAllFields(parameter);
            }

            for (Field field : fields) {
                this.setFieldValue(field, parameter, sysUser, 2);
            }
        }
        return invocation.proceed();
    }

    private void setFieldValue(Field field, Object parameter, LoginUser sysUser, int type){

        log.debug("------field.name------" + field.getName());
        try {
            if (type == 1 && "createBy".equals(field.getName())) {
                field.setAccessible(true);
                Object local_createBy = field.get(parameter);
                field.setAccessible(false);
                if (local_createBy == null || local_createBy.equals("")) {
                    String value = "系统";
                    if (sysUser != null) {
                        // 登录人账号
                        value = sysUser.getUsername();
                    }
                    // 没有登录人员，默认系统
                    field.setAccessible(true);
                    field.set(parameter, value);
                    field.setAccessible(false);
                }
            }
            // 注入创建时间
            else if (type == 1 && "createTime".equals(field.getName())) {
                field.setAccessible(true);
                Object local_createDate = field.get(parameter);
                field.setAccessible(false);
                if (local_createDate == null || local_createDate.equals("")) {
                    field.setAccessible(true);
                    field.set(parameter, new Date());
                    field.setAccessible(false);
                }
            }
            //注入部门编码
            else if ("sysOrgCode".equals(field.getName())) {
                field.setAccessible(true);
                String local_sysOrgCode = field.get(parameter) == null ? null : String.valueOf(field.get(parameter));
                field.setAccessible(false);
                if (StringUtils.isBlank(local_sysOrgCode)) {
                    String companyId = ReflectHelper.getFieldValueByName("companyId", parameter) == null
                            ? null : String.valueOf(ReflectHelper.getFieldValueByName("companyId", parameter));
                    if (StringUtils.isNotBlank(companyId)){
                        if (sysBaseAPI == null){
                            sysBaseAPI = (ISysBaseAPI) SpringContextUtils.getBean("sysBaseApiImpl");
                        }
                        field.setAccessible(true);
                        field.set(parameter, sysBaseAPI.getDepartOrgCodeById(companyId));
                        field.setAccessible(false);
                    }
                    // 获取登录用户信息
                    else if (type == 1 && sysUser != null) {
                        field.setAccessible(true);
                        field.set(parameter, sysUser.getOrgCode());
                        field.setAccessible(false);
                    }
                }
            }
            else if ("updateBy".equals(field.getName())) {
                //获取登录用户信息
                if (sysUser != null) {
                    // 登录账号
                    field.setAccessible(true);
                    field.set(parameter, sysUser.getUsername());
                    field.setAccessible(false);
                }
            }
            else if ("updateTime".equals(field.getName())) {
                field.setAccessible(true);
                field.set(parameter, new Date());
                field.setAccessible(false);
            }
            //注入公司ID
            else if (type == 1 && "companyId".equals(field.getName())) {
                field.setAccessible(true);
                Object local_companyId = field.get(parameter);
                field.setAccessible(false);
                if (local_companyId == null || local_companyId.equals("")) {
                    // 获取登录用户信息
                    if (sysUser != null) {
                        field.setAccessible(true);
                        field.set(parameter, sysUser.getCurrentCompanyId());
                        field.setAccessible(false);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // TODO Auto-generated method stub
    }

}
